/*
 * Copyright 2002-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hsc.lock.interceptor;

import com.hsc.lock.interceptor.store.SimpleLockErrorHandler;
import com.hsc.lock.interceptor.store.StoreErrorHandler;
import com.hsc.lock.store.LockStore;
import org.springframework.lang.Nullable;
import org.springframework.util.function.SingletonSupplier;

/**
 * A base component for invoking {@link LockStore} operations and using a
 * configurable {@link StoreErrorHandler} when an exception occurs.
 *
 * @author Stephane Nicoll
 * @author Juergen Hoeller
 * @see StoreErrorHandler
 * @since 4.1
 */
public abstract class AbstractStoreInvoker {

    protected SingletonSupplier<StoreErrorHandler> errorHandler;


    protected AbstractStoreInvoker() {
        this.errorHandler = SingletonSupplier.of(SimpleLockErrorHandler::new);
    }

    protected AbstractStoreInvoker(StoreErrorHandler errorHandler) {
        this.errorHandler = SingletonSupplier.of(errorHandler);
    }


    /**
     * Set the {@link StoreErrorHandler} instance to use to handle errors
     * thrown by the cache provider. By default, a {@link SimpleLockErrorHandler}
     * is used who throws any exception as is.
     */
    public void setErrorHandler(StoreErrorHandler errorHandler) {
        this.errorHandler = SingletonSupplier.of(errorHandler);
    }

    /**
     * Return the {@link StoreErrorHandler} to use.
     */
    public StoreErrorHandler getErrorHandler() {
        return this.errorHandler.obtain();
    }


    @Nullable
    protected LockStore.ValueWrapper doPutIfAbsent(LockStore cache, Object key, @Nullable Object value) {
        try {
            return cache.putIfAbsent(key,value);
        } catch (RuntimeException ex) {
            getErrorHandler().handleCacheGetError(ex, cache, key);
            return null;  // If the exception is handled, return a cache miss
        }
    }

    /**
     * Execute {@link LockStore#get(Object)} on the specified {@link LockStore} and
     * invoke the error handler if an exception occurs. Return {@code null}
     * if the handler does not throw any exception, which simulates a cache
     * miss in case of error.
     *
     * @see LockStore#get(Object)
     */
    @Nullable
    protected LockStore.ValueWrapper doGet(LockStore cache, Object key) {
        try {
            return cache.get(key);
        } catch (RuntimeException ex) {
            getErrorHandler().handleCacheGetError(ex, cache, key);
            return null;  // If the exception is handled, return a cache miss
        }
    }

    /**
     * Execute {@link LockStore#put(Object, Object)} on the specified {@link LockStore}
     * and invoke the error handler if an exception occurs.
     */
    protected void doPut(LockStore cache, Object key, @Nullable Object result) {
        try {
            cache.put(key, result);
        } catch (RuntimeException ex) {
            getErrorHandler().handleCachePutError(ex, cache, key, result);
        }
    }

    /**
     * Execute {@link LockStore#evict(Object)}/{@link LockStore#evictIfPresent(Object)} on the
     * specified {@link LockStore} and invoke the error handler if an exception occurs.
     */
    protected void doEvict(LockStore cache, Object key, boolean immediate) {
        try {
            if (immediate) {
                cache.evictIfPresent(key);
            } else {
                cache.evict(key);
            }
        } catch (RuntimeException ex) {
            getErrorHandler().handleCacheEvictError(ex, cache, key);
        }
    }

    /**
     * Execute {@link LockStore#clear()} on the specified {@link LockStore} and
     * invoke the error handler if an exception occurs.
     */
    protected void doClear(LockStore cache, boolean immediate) {
        try {
            if (immediate) {
                cache.invalidate();
            } else {
                cache.clear();
            }
        } catch (RuntimeException ex) {
            getErrorHandler().handleCacheClearError(ex, cache);
        }
    }

}
